#! /bin/bash
# shadowsocks 的启停
DIR="$( cd "$( dirname "$0"  )" && pwd  )" 
pid=0
action=$1
logFile="run.log"

# 停止服务
stop_servie() {
    # 进程存在就干掉
    pid=`get_pid`
    if [[ $pid != '' ]];then
        kill -9 $pid
    fi
}
# 开始服务
start_service() {
    echo "starting service..."
    echo "starting service..." >> $DIR/$logFile
    # 后台运行服务
    nohup python $DIR/shadowsocks/server.py -c $DIR/user-config.json m> $DIR/$logFile 2>&1 &
    # 获取PID判断是否存在
    pid=`get_pid`
    if [[ $pid == '' ]];then
        echo "start shadowsocksR service failed." >> $DIR/$logFile
        exit 1
    fi
}
# 重启服务 
restart_service() {
    # 先停止服务再开始
    stop_servie
    start_service
}
# 获取正在运行的gogs的pid
get_pid() {
    pid=`ps -ef | grep "$DIR/shadowsocks/server.py" | grep -v grep | awk '{print $2}'`
    echo $pid
}
# 注册为centOS服务
register_service() {
    echo -e " 
    [Unit]
    Description=ShadowsocksR service
    After=network.target

    [Service]
    Type=simple
    ExecStart=$DIR/ssr-service.sh start
    ExecReload=$DIR/ssr-service.sh restart
    ExecStop=$DIR/ssr-service.sh stop
    " > /lib/systemd/system/ssr.service
}
pid=`get_pid`

case $action in
    "start" ) 
    start_service
    ;;
    "stop" )
    stop_servie
    ;;
    "restart" )
    restart_service
    ;;
    "pid" )
    get_pid
    ;;
    "register" )
    register_service
    ;;
esac